package main

import (
	"fmt"
	"log"
	"net/http"

	"gitee.com/itsos/wxsdk/wxchat"
)

func main() {

	http.Handle("/", http.FileServer(http.Dir("./static")))
	http.HandleFunc("/snsapi_base", func(w http.ResponseWriter, r *http.Request) {
		values := r.URL.Query()
		url, err := wxchat.NewAuthorize().SnsApiBase(values.Get("callback"), "wechat")
		if err != nil {
			log.Fatal(err)
		}
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprintf(w, "%s\n", url)
	})

	http.HandleFunc("/snsapi_auth", func(w http.ResponseWriter, r *http.Request) {
		values := r.URL.Query()
		tokens, err := wxchat.NewAuthorize().SnsAccessToken(values.Get("code"))
		if err != nil {
			log.Fatal(err)
		}
		fmt.Fprintf(w, "%s\n", tokens.Openid)
	})

	port := "8080"
	log.Printf(fmt.Sprintf("About to listen on %s. Go to http://localhost:%s/", port, port))
	err := http.ListenAndServe(":"+port, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
